package evaleto.ecodroid.device;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.provider.Settings;
import android.util.Log;

public class Cell implements Idevice{
	private static String TAG="Ecodroid::Cell";
	/**
	 * Settings.System.AIRPLANE_MODE_RADIOS
	 * A comma separated list of radios that need to be disabled when airplane mode is on.
	 *   Settings.System.RADIO_BLUETOOTH
	 *   Settings.System.RADIO_CELL
	 *   Settings.System.RADIO_WIFI
	 */
	private static String AIRPLANE_MODE_RADIOS=Settings.System.RADIO_CELL;
	private Context context;

	
	public Cell(Context context) {
		this.context=context;
		init();
	}

	private void init(){
		String mode=Settings.System.getString(
			      context.getContentResolver(), 
			      Settings.System.AIRPLANE_MODE_RADIOS);
				
		Log.i(TAG, "default AIRPLANE_MODE_RADIOS="+mode);
		
		// set airplane mode to Cell only
		Settings.System.putString(
			      context.getContentResolver(), 
			      Settings.System.AIRPLANE_MODE_RADIOS, AIRPLANE_MODE_RADIOS);
				
	}
	public boolean isEnable(){
		boolean isEnabled = Settings.System.getInt(
			      context.getContentResolver(), 
			      Settings.System.AIRPLANE_MODE_ON, 0) == 1;
		return isEnabled;
	}
	
	public void toggle(){
		boolean isEnabled = isEnable();

		// toggle and post an intent to reload
		setEnable(!isEnabled);
	}
	
	public void setEnable(boolean enable){
		Settings.System.putInt(
			      context.getContentResolver(),
			      Settings.System.AIRPLANE_MODE_ON, enable ? 0 : 1);
		
		
		Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
		intent.putExtra("state", enable);
		context.sendBroadcast(intent);		
	}
	
	public void addOnChange(BroadcastReceiver receiver){
		IntentFilter intentFilter = new IntentFilter("android.intent.action.SERVICE_STATE");
		context.registerReceiver(receiver, intentFilter);		
	}
}
